package win.liumian.sso.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static win.liumian.sso.util.Constants.SSO_TICKET;
import static win.liumian.sso.util.Constants.SSO_SERVER_URL;

/**
 * @author liumian
 */
public class SsoHttpClient {

    private CloseableHttpClient httpClient;


    public SsoHttpClient() {
        httpClient = HttpClientBuilder.create().build();
    }

    public boolean isLegalTicket(String ssoTicket) {
        try {
            HttpPost post = new HttpPost(SSO_SERVER_URL + "/auth");
            JSONObject requestBody = new JSONObject();
            requestBody.put(SSO_TICKET, ssoTicket);
            HttpEntity requestEntity = new StringEntity(requestBody.toString(), ContentType.APPLICATION_JSON);
            post.setEntity(requestEntity);

            CloseableHttpResponse response = httpClient.execute(post);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    JSONObject responseJson = JSONObject.parseObject(EntityUtils.toString(entity, StandardCharsets.UTF_8));
                    return responseJson.getJSONObject("data").getBoolean("isLogin");
                }
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void destroy() {
        try {
            httpClient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
